from django.shortcuts import render
from apps.oauth.models import OAuthQQUser
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
import logging
from apps.oauth.util import check_access_token, generate_access_token
from django.contrib.auth import login
import json
import re
from django_redis import get_redis_connection
from apps.users.models import User
from django.db import DatabaseError
logger = logging.getLogger('django')
# Create your views here.
class QQUserView(View):
    '''QQ扫码回掉处理
    GET /oauth_callback/
    '''
    def get(self, request):
        #从request中拿到code
        code = request.GET.get('code')
        #判断code是否存在
        if not code:
            return http.JsonResponse({'code':400,
                                      'errmsg':'缺少code参数'})
        #如果code已存在就用code 向ＱＱ拿accosstaken
        #创建QQ链接实例
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        try:
            accosstaken = oauth.get_access_token(code)
            #通过accosstaken拿openid
            openid = oauth.get_open_id(accosstaken)
        except Exception as e:
            logger.error(e)
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'oauth2.0认证失败, 即获取qq信息失败'})
        try:
            #　下面是否判断绑定用户
            #从数据库中查找openid
            oauth_qq =OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            #如果没有美多商城的用户就跳转到用户注册
            #使用定义的加密工具将openid加密返回给前端
            access_token = generate_access_token(openid)
            return http.JsonResponse({'code': 300,
                                      'errmsg': 'ok',
                                      'access_token': access_token})

        else:
            # 如果有就跳转到登录页
            user = oauth_qq.user
            # 实现状态保持
            login(request, user)
            #设置cookie返回response
            response = http.JsonResponse({'code':0,
                                          'errmsg':'ok'})

            response.set_cookie('username', user.username, max_age=3600*24*14)
            return response




    def post(self, request):
        '''用户ＱＱ登录绑定用户视图'''
        #拿到数据
        user_info = request.body.decode()
        user_dict = json.loads(user_info)
        mobile = user_dict.get('mobile')
        password = user_dict.get('password')
        sms_code = user_dict.get('sms_code')
        access_token = user_dict.get('access_token')
        #分离出openid
        openid = check_access_token(access_token)

        #效验参数
        #查看数据是否齐全
        if not all([mobile, password, sms_code]):
            return http.JsonResponse({'code':400,
                                      'errmsg':'缺少必要的参数'})
        #检查手机号
        if not re.match('^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code':400,
                                      'errmsg':'手机号输入错误'})

        #检查密码
        if not re.match('^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code':400,
                                      'errmsg':'密码输入错误'})

        #验证短信是否一致
        #创建redis链接对象
        redis_count = get_redis_connection('verify_code')

        #从redis中获取短信验证码
        sms_code_server = redis_count.get('sms_%s'% mobile)

        if sms_code_server is None:
            return http.JsonResponse({'code':400,
                                      'errmsg':'验证码失效'})

        if sms_code != sms_code_server.decode():
            return http.JsonResponse({'code':400,
                                      'errmsg':'输入的验证码有误'})


        #判断用户是否存在如果存在检查密码，不存在写入数据
        try:
            user = User.objects.get(mobile=mobile)

        except User.DoesNotExist:
            #说明没有这个用户
            User.objects.create_user(username=mobile,
                                     password=password,
                                     mobile=mobile)
        else:
            #说明有这个用户
            if not user.check_password(password):
                return http.JsonResponse({'code':400,
                                          'errmsg':'密码输入错误'})


        #代码执行到此说明新用户被创建所以要将qq登录的openid与用户绑定
        try:
            OAuthQQUser.objects.create(openid=openid,
                                       user=user)
        except DatabaseError:
            return http.JsonResponse({'code':400,
                                      'errmsg':'数据库数据添加错误'})

        #代码执行到此说明用户绑定完成下面做状态保持并登录设置cookie
        login(request, user)

        response = http.JsonResponse({'code':0,
                    'errmsg':'登录成功'})
        response.set_cookie('username',
                            user.username,
                            max_age=3600*24*14)
        return response




class QQURLView(View):
    """QQ登录扫码链接
    GET /qq/authorization/
    """
    def get(self, request):
        #接收next参数
        next = request.GET.get('next', '/')

        #生成qq链接url对象
        oauth =OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                       client_secret=settings.QQ_CLIENT_SECRET,
                       redirect_uri=settings.QQ_REDIRECT_URI,
                       state=next)
        #调用ＱＱ链接请求接口
        login_url = oauth.get_qq_url()
        #将请求的url返回给前端
        return http.JsonResponse({'code':0,
                                  'errmsg':'ok',
                                  'login_url':login_url})
